import Vue from 'vue';
function RanderTableUtil() {
  // 动态渲染模板表格
  this.renderTemplateTable = function (tableStructure, containerId) {
    let template = this.getTableTemplate(tableStructure, false);
    // console.log("template:::", template);
    let TableTemp = Vue.extend({
      template: template,
      data: function () {
        return {
          templateTableData: [
            { aaa: "" },
            { aaa: "" },
            { aaa: "" },
            { aaa: "" },
            { aaa: "" }
          ]
        }
      }
    });
    let tableTemp = new TableTemp();
    this.mountTable(tableTemp, containerId);
    return tableTemp;
  }

  this.renderTemplateOperationTable = function (tableStructure, fieldNames, tableData, containerId) {
    let template = this.getTableTemplate(tableStructure, true);
    // console.log("renderTemplateOperationTable:::", template);
    let TableTemp = Vue.extend({
      template: template,
      props: {
        fieldNames: Array,
        templateTableData: Array
      },
      data: function () {
        return {
          // templateTableData: []
        }
      },
      methods: {
        addOneRow() {
          let emptyTableData = {
            isEdit: true
          };
          for (let fieldName of this.fieldNames) {
            emptyTableData[fieldName] = "";
          }
          this.templateTableData.push(emptyTableData);
        },
        removeOneRow(row) {
          this.$confirm("将要删除当前行，是否继续？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if (row.id) {
              this.$axios.get(`/api/statistics/statistical-record/delete-record?id=${row.id}`)
                .then(res => {
                  if (res.data.code === 200) {
                    let index = this.templateTableData.indexOf(row);
                    this.templateTableData.splice(index, 1);
                  } else {
                    this.$message.error(res.data.message);
                  }
                })
            } else {
              let index = this.templateTableData.indexOf(row);
              this.templateTableData.splice(index, 1);
              this.$message.success("已成功删除");
            }
          }).catch(() => {
            this.$message.info("已取消删除");
          })
        },
        resetAllDataNoEdit() {
          this.templateTableData.forEach(data => {
            data.isEdit = false;
          });
        },
        getTableData() {
          return this.templateTableData;
        }
      }
    });
    let tableTemp = new TableTemp({
      propsData: {
        fieldNames: fieldNames,
        templateTableData: tableData
      }
    });
    this.mountTable(tableTemp, containerId);
    return tableTemp;
  }

  // 挂载表格
  this.mountTable = function (tableTemp, containerId) {
    let container = document.getElementById(containerId);
    // 删除容器下所有子节点
    while (container.hasChildNodes()) {
      container.removeChild(container.firstChild)
    }
    // 创建新的子节点用于挂载动态生成的table
    let tableContainer = document.createElement("div");
    tableContainer.setAttribute("id", "table-container");
    container.appendChild(tableContainer);
    tableTemp.$mount("#table-container");
  }

  // 获取表格template代码
  this.getTableTemplate = function (tableStructure, isOperation) {
    let operationTemplate = `<el-table-column
    fixed="right"
    label="操作"
    width="100">
    <template slot-scope="scope">
      <el-button v-if="scope.row.isEdit" type="text" size="small" @click="scope.row.isEdit=false">确定</el-button>
      <el-button v-else type="text" size="small" @click="scope.row.isEdit=true">编辑</el-button>
      <el-button type="text" size="small" @click="removeOneRow(scope.row)">移除</el-button>
    </template>
  </el-table-column>`;
    let templateStr = this.recurGenerateTable(tableStructure, isOperation);
    let template = `<el-table :data="templateTableData" border style="width:100%">${templateStr}${isOperation ? operationTemplate : ''}</el-table>`;
    return template;
  }

  // 递归的获取表格模板代码
  this.recurGenerateTable = function (tableStructure, isOperation) {
    let templateStr = "";
    for (let key in tableStructure) {
      let structure = tableStructure[key];
      templateStr += `<el-table-column label=${structure.label} ${structure.prop ? "prop=" + structure.prop + ">" : ">"}`;
      if (structure.prop && isOperation) {
        templateStr += `<template slot-scope="scope">
        <el-input v-if="scope.row.isEdit" v-model="scope.row['${structure.prop}']" placeholder="请填写"></el-input>
        <span v-else>{{scope.row['${structure.prop}']}}</span>
      </template>`
      }
      if (structure.children) {
        let temp = this.recurGenerateTable(structure.children, isOperation);
        templateStr += temp + "</el-table-column>";
      } else {
        templateStr += "</el-table-column>";
      }
    }
    return templateStr;
  }
}

export default new RanderTableUtil();